package com.fortune.service.ananlysis;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.FileUtils;
import com.fortune.dal.model.Bank;
import com.fortune.service.ananlysis.dto.BillMailInfoDTO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import java.io.File;

public abstract class AbstractAnanlysis implements AnanlysisService {

    public String getContent(Part part) throws BusinessException {
        try {
            if (part.isMimeType("text/plain")) {
                // text/plain 类型
                return (String) part.getContent();
            } else if (part.isMimeType("text/html")) {
                // text/html 类型
                String str = (String) part.getContent();
                return new String(str.getBytes(), "utf-8");
            } else if (part.isMimeType("multipart/*")) {
                // multipart/*
                Multipart multipart = (Multipart) part.getContent();
                int counts = multipart.getCount();
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < counts; i++) {
                    sb.append(getContent(multipart.getBodyPart(i)));
                }
                return sb.toString();
            } else if (part.isMimeType("message/rfc822")) {
                // message/rfc822
                return getContent((Part) part.getContent());
            }
        } catch (Exception ex) {

        }
        return null;
    }

    @Override
    public BillMailInfoDTO ananlysis(Bank bank, Message me) throws BusinessException {
        BillMailInfoDTO billMailInfoDTO = null;
        try {
            billMailInfoDTO = new BillMailInfoDTO();
            String content = getContent(me);
            Document document = Jsoup.parse(content);
            ananlysis(billMailInfoDTO, document);
            billMailInfoDTO.setBankId(bank.getId());
            FileUtils.writeFile(new File("C:\\tmp\\" + bank.getName() +System.currentTimeMillis()+".html" ),content);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        }
        return billMailInfoDTO;
    }

    abstract void ananlysis(BillMailInfoDTO billMailInfoDTO, Document document) throws BusinessException;


}
